package com.lwt.controller.admin;

import com.lwt.po.User;
import com.lwt.service.UserService;
import com.lwt.util.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

/**
 * @program: blog
 * @author: 关键我是大怪
 * @create: 2021-07-29 16:20
 */
@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String loginPage() {

        return "admin/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, Model model, HttpSession session) {
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登陆数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, MD5Utils.code(password));

        try {
            subject.login(token);//执行登陆的方法，如果没有异常就OK了
            User user = userService.queryUserByName(username);
            user.setPassword(null);
            session.setAttribute("user", user);
            return "admin/index";
        } catch (UnknownAccountException e) {//用户名不存在
            model.addAttribute("message", "用户名和密码错误");
            return "admin/login";
        } catch (IncorrectCredentialsException e) {//密码错误
            model.addAttribute("message", "用户名和密码错误");
            return "admin/login";

        }

    }


    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }

}
